package com.vhall.component.init;

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author shimingming
 * @since 2023/9/6 17:43
 */
@Component
public class ImageLoader {

    private final ResourceLoader resourceLoader;

    public ImageLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    public BufferedImage loadImage(String imageName) throws IOException {
        Resource resource = resourceLoader.getResource("classpath:" + imageName);

        try (InputStream inputStream = resource.getInputStream()) {
            return ImageIO.read(inputStream);
        }
    }

    public byte[] convertImageToByteArray(BufferedImage image, String format) throws IOException {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(image, format, baos);
            baos.flush();
            return baos.toByteArray();
        }
    }
}